package org.gl.util;

public class ByteUtil {
	public static int byteArrayToInt(byte[] b, int offset) {
		int value = 0;
		for (int i = 0; i < 4; i++) {
			int shift = (4 - 1 - i) * 8;// Int has 4*8 = 32 bits
			value += (b[i + offset] & 0x000000FF) << shift;// BUMA in java,so
															// must &0x000000FF
		}
		return value;
	}

	public static int byteArrayToShort(byte[] b, int offset) {
		int value = 0;
		for (int i = 0; i < 2; i++) {// short only 2*8 = 16 bits
			int shift = (2 - 1 - i) * 8;
			value += (b[i + offset] & 0x000000FF) << shift;
		}
		return value;
	}

	public static int byteToint(byte b, int offset) {
		int value = 0;
		value += b & 0x000000FF;
		return value;
	}

	public static byte[] intTobByteArray(int i) {
		byte[] result = new byte[4];

		result[0] = (byte) (i >> 24);
		result[1] = (byte) (i >> 16);
		result[2] = (byte) (i >> 8);
		result[3] = (byte) (i /* >> 0 */);

		return result;
	}
}
